package 代码随想录.数组.长度最小的子数组;

/** lc209. 长度最小的子数组
 * link:https://leetcode-cn.com/problems/minimum-size-subarray-sum/
 * @author ChenweiLin
 * @create 2021-11-30 14:56
 */
public class minimumSizeSubarraySum {
    public static void main(String[] args) {
        System.out.println(minSubArrayLen(15, new int[]{1, 2, 3, 4, 5}));
    }

    public static int minSubArrayLen(int target, int[] nums) {
        //滑动窗口
        int left = 0;
        int right = 0;
        int len = Integer.MAX_VALUE;//答案的长度
        int total = 0;
        //正整数数组
        for (; right < nums.length; right++) {
            total += nums[right];//右窗口的值依次放进去
            while (total >= target){//要用while不能用if，因为左窗口不一定只退出一个数，可能退多个
                len = Math.min(len, right-left+1);//获取最小的len
                total -=nums[left++];//left指针向后移动，total去掉原来左窗口的数字
            }
        }
        return len == Integer.MAX_VALUE? 0:len;
    }
}
